package vtt.android.sportnews.database;

import vtt.android.library.VttBaseApplication;
import vtt.android.library.utils.VttLog;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;

public class LpsDAO {

	private static LpsDAO instance = null;
	
	VttLog log = new VttLog("ResultDAO", VttBaseApplication.isDebuggable);
	// field database
	public static String TABLE_QUESTIONNAIRE = "questionnaire";
	public static String TABLE_CHALLENGE_DATE = "challenge_date";

	// Database fields
	private SQLiteDatabase db;
	private MySQLiteOpenHelper dbHelper;
	
	public static LpsDAO getInstance(Context context){
		if(instance == null){
			instance = new LpsDAO(context);
		}
		return instance;
	}

	private LpsDAO(Context context) {
		dbHelper = new MySQLiteOpenHelper(context);
	}

	public void open() throws SQLException {
		if(db == null) {
			db = dbHelper.getWritableDatabase();
		}
		
	}

	public void close() {
		dbHelper.close();
		db = null;
	}

	
	public void createCacheTable(SQLiteDatabase db) {
		String sql = " CREATE TABLE lps_cache ( " 
				+ " id INTEGER, " 
				+ " content TEXT " 
				+ ");";

		db.execSQL(sql);
		db.execSQL("insert into [lps_cache] ([id], [content]) values (1, '');");
	}
	
	// load cache data
	public String loadCacheData() {
		String cacheData = "";
		// Select All Query
		String selectQuery = " SELECT content FROM lps_cache where id = 1;";
		Cursor cursor = db.rawQuery(selectQuery, null);
		// looping through all rows and adding to list
		if (cursor.moveToFirst()) {
			do {
				cacheData = cursor.getString(0);
			} while (cursor.moveToNext());
		}
		return cacheData;
	}
	
	// save cache data
	public void saveCacheData(String data){
		ContentValues params = new ContentValues();
		params.put("content", data);
	    db.update("lps_cache", params, "id = 1", null);
	}
}
